<template>
    <div class="product-edit-container">
        <el-card shadow="never">
            <template #header>
                <div class="card-header">
                    <span>{{ isEdit ? '编辑商品' : '添加商品' }}</span>
                </div>
            </template>

            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="product-form">
                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入商品名称" />
                </el-form-item>

                <el-form-item label="商品价格" prop="price">
                    <el-input-number v-model="form.price" :min="0" :precision="2" :step="1" />
                </el-form-item>

                <el-form-item label="商品库存" prop="stock">
                    <el-input-number v-model="form.stock" :min="0" :step="1" />
                </el-form-item>

                <el-form-item label="商品分类" prop="categoryId">
                    <el-select v-model="form.categoryId" placeholder="请选择商品分类" style="width: 100%">
                        <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="商品品牌" prop="brandId">
                    <el-select v-model="form.brandId" placeholder="请选择商品品牌" style="width: 100%">
                        <el-option v-for="item in brandOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="商品主图" prop="image">
                    <el-upload class="product-image-upload" action="http://localhost:8081/api/admin/upload/image"
                        :show-file-list="false" :on-success="handleImageSuccess" :before-upload="beforeImageUpload">
                        <el-image v-if="form.image" :src="formatImageUrl(form.image)" class="preview-image"
                            fit="cover" />
                        <div v-else class="upload-placeholder">
                            <el-icon><el-icon-plus /></el-icon>
                        </div>
                        <div class="upload-tip">点击上传图片</div>
                    </el-upload>
                </el-form-item>

                <el-form-item label="商品详情" prop="description">
                    <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入商品详情描述" />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submitForm" :loading="submitting">保存</el-button>
                    <el-button @click="goBack">取消</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus as ElIconPlus } from '@element-plus/icons-vue'
import { getProductDetail, createProduct, updateProduct } from '../../api/product'
import { getCategoryList } from '../../api/category'
import { getBrandList } from '../../api/brand'
import { formatImageUrl } from '../../utils/index'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const submitting = ref(false)
const categoryOptions = ref([])
const brandOptions = ref([])

// 判断是编辑还是添加
const isEdit = computed(() => {
    return route.params.id !== undefined
})

// 表单数据
const form = reactive({
    id: undefined,
    name: '',
    price: 0,
    stock: 0,
    categoryId: undefined,
    brandId: undefined,
    image: '',
    description: ''
})

// 表单验证规则
const rules = {
    name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
    price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
    stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }],
    categoryId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
    brandId: [{ required: true, message: '请选择商品品牌', trigger: 'change' }],
    image: [{ required: true, message: '请上传商品主图', trigger: 'change' }]
}

// 获取商品详情
const getDetail = async (id) => {
    try {
        const res = await getProductDetail(id)
        if (res.code === 200 && res.data) {
            const data = res.data
            form.id = data.id
            form.name = data.name
            form.price = data.price
            form.stock = data.stock
            form.categoryId = data.category?.id
            form.brandId = data.brand?.id
            form.image = data.image
            form.description = data.description || ''
        } else {
            ElMessage.error('获取商品信息失败')
        }
    } catch (error) {
        console.error('获取商品详情失败:', error)
        ElMessage.error('获取商品详情失败')
    }
}

// 获取分类列表
const fetchCategories = async () => {
    try {
        const res = await getCategoryList()
        categoryOptions.value = (res.data || []).map(item => ({
            value: item.id,
            label: item.name
        }))
    } catch (error) {
        console.error('获取分类列表失败:', error)
    }
}

// 获取品牌列表
const fetchBrands = async () => {
    try {
        const res = await getBrandList()
        brandOptions.value = (res.data || []).map(item => ({
            value: item.id,
            label: item.name
        }))
    } catch (error) {
        console.error('获取品牌列表失败:', error)
    }
}

// 提交表单
const submitForm = () => {
    formRef.value.validate(valid => {
        if (!valid) return

        submitting.value = true
        const submitData = { ...form }

        // 判断是编辑还是新增
        const request = isEdit.value
            ? updateProduct(form.id, submitData)
            : createProduct(submitData)

        request.then(res => {
            if (res.code === 200) {
                ElMessage.success(`${isEdit.value ? '更新' : '添加'}商品成功`)
                goBack()
            } else {
                ElMessage.error(res.message || `${isEdit.value ? '更新' : '添加'}商品失败`)
            }
        }).catch(error => {
            console.error(`${isEdit.value ? '更新' : '添加'}商品失败:`, error)
            ElMessage.error(`${isEdit.value ? '更新' : '添加'}商品失败`)
        }).finally(() => {
            submitting.value = false
        })
    })
}

// 图片上传前验证
const beforeImageUpload = (file) => {
    const isJPG = file.type === 'image/jpeg'
    const isPNG = file.type === 'image/png'
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJPG && !isPNG) {
        ElMessage.error('上传图片只能是 JPG 或 PNG 格式!')
        return false
    }

    if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!')
        return false
    }

    return true
}

// 图片上传成功回调
const handleImageSuccess = (response) => {
    if (response.code === 200 && response.data) {
        form.image = response.data.url
    } else {
        ElMessage.error('图片上传失败')
    }
}

// 返回列表页
const goBack = () => {
    router.push('/product/list')
}

// 初始化
onMounted(async () => {
    // 先获取分类和品牌列表
    await Promise.all([fetchCategories(), fetchBrands()])

    // 如果是编辑模式，获取商品详情
    if (isEdit.value) {
        getDetail(route.params.id)
    }
})
</script>

<style scoped>
.product-edit-container {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.product-form {
    max-width: 800px;
}

.product-image-upload {
    text-align: center;
}

.preview-image {
    width: 150px;
    height: 150px;
    display: block;
    margin-bottom: 10px;
}

.upload-placeholder {
    width: 150px;
    height: 150px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #8c939d;
    font-size: 28px;
    background-color: #fbfdff;
    cursor: pointer;
    margin-bottom: 10px;
}

.upload-placeholder:hover {
    border-color: #409EFF;
}

.upload-tip {
    color: #606266;
    font-size: 12px;
}
</style>